import React from 'react';
import { getDisplayTimeBySeconds } from './utils';

export default function CurrentTime(props) {
    const { audio } = props;
    const [currentTime, setCurrentTime] = React.useState(0);

    const handleAudioCurrentTimeChange = e => {
        setCurrentTime(e.target.currentTime);
    };

    React.useEffect(() => {
        setCurrentTime(audio.currentTime);
        audio.addEventListener('timeupdate', handleAudioCurrentTimeChange);
        audio.addEventListener('loadedmetadata', handleAudioCurrentTimeChange);
        return () => {
            audio.removeEventListener('timeupdate', handleAudioCurrentTimeChange);
            audio.removeEventListener('loadedmetadata', handleAudioCurrentTimeChange);
        };
    }, [audio]);

    return getDisplayTimeBySeconds(currentTime);
}
